package com.banciyuan.wallpaper.page.display;

import android.animation.ObjectAnimator;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banciyuan.wallpaper.R;
import com.banciyuan.wallpaper.bean.Item;
import com.banciyuan.wallpaper.page.DownLoadActivity;
import com.banciyuan.wallpaper.page.display.lazy.BasePageFragment;
import com.banciyuan.wallpaper.page.setting.SettingActivity;
import com.banciyuan.wallpaper.setting.SettingConfig;
import com.banciyuan.wallpaper.toast.MyToast;
import com.banciyuan.wallpaper.util.ScreenShots;
import com.banciyuan.wallpaper.util.UIUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.pnikosis.materialishprogress.ProgressWheel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Random;

/**
 * Created by squall on 2016/7/29.
 */
public class DisplayFragment extends BasePageFragment implements View.OnClickListener {

    public static final int GO_SETTING = 1000;
    private ImageView loading_back;
    private ImageView display_setting;
    private LinearLayout ll_loading;
    private TextView download_tv;
    private TextView wallpaper_tv;
    private TextView share_tv;
    private RelativeLayout rl_info;
    private ProgressWheel progressWheel;

    private TextView author;
    private ImageView avatar;
    private TextView info;

    private Item item;
    private SuccessListener successListener;
    private boolean setting_process;
    private boolean download_process;
    private int[] colors;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        item = getArguments().getParcelable("item");
        successListener = new SuccessListener();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_WALLPAPER_CHANGED);
        getActivity().registerReceiver(successListener, intentFilter);

        colors = new int[]{getResources().getColor(R.color.blue)
                , getResources().getColor(R.color.light_blue)
                , getResources().getColor(R.color.middle_blue)
                , getResources().getColor(R.color.dark_blue)
                , getResources().getColor(R.color.yellow)
                , getResources().getColor(R.color.orange)
                , getResources().getColor(R.color.red)};
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(successListener);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View viewroot = inflater.inflate(R.layout.display_fragment, container, false);
        loading_back = (ImageView) viewroot.findViewById(R.id.loading_back);
        ll_loading = (LinearLayout) viewroot.findViewById(R.id.loading_layout);
        display_setting = (ImageView) viewroot.findViewById(R.id.display_setting);
        download_tv = (TextView) viewroot.findViewById(R.id.download_tv);
        rl_info = (RelativeLayout) viewroot.findViewById(R.id.info_container);
        wallpaper_tv = (TextView) viewroot.findViewById(R.id.set_wallpaper_tv);
        share_tv = (TextView) viewroot.findViewById(R.id.share_tv);
        progressWheel = (ProgressWheel) viewroot.findViewById(R.id.progress_wheel);

        loading_back.setDrawingCacheEnabled(true);

        author = (TextView) viewroot.findViewById(R.id.author_name);
        avatar = (ImageView) viewroot.findViewById(R.id.user_head);
        info = (TextView) viewroot.findViewById(R.id.author_info);

        display_setting.setOnClickListener(this);
        wallpaper_tv.setOnClickListener(this);
        download_tv.setOnClickListener(this);
        rl_info.setOnClickListener(this);
        loading_back.setOnClickListener(this);
        share_tv.setOnClickListener(this);

        Random random = new Random();
        int index = random.nextInt(7);
        progressWheel.setBarColor(colors[index]);

        return viewroot;
    }

    //    private void setImageMove(final int x) {
    //
    //        new Handler().postDelayed(new Runnable() {
    //            @Override
    //            public void run() {
    //                Matrix matrix = new Matrix();
    //                matrix.postTranslate(x, 0);
    //                loading_back.setImageMatrix(matrix);
    //                setImageMove(x + 1);
    //            }
    //        }, 25);
    //    }
    //
    private Point getScreen() {
        WindowManager wm = (WindowManager) getActivity().getSystemService(getActivity().WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point point = new Point();
        display.getSize(point);
        return point;
    }


    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.info_container:
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        ScreenShots screenShots = new ScreenShots((View) loading_back.getParent());
                        screenShots.takeShot();
                    }
                });
                intent = new Intent(getActivity(), DownLoadActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                break;
            case R.id.download_tv:
                setDownload();
                break;
            case R.id.set_wallpaper_tv:
                setWallpaper();
                break;
            case R.id.display_setting:
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        ScreenShots screenShots = new ScreenShots((View) loading_back.getParent());
                        screenShots.takeShot();
                    }
                });
                intent = new Intent(getActivity(), SettingActivity.class);
                startActivityForResult(intent, GO_SETTING);
                getActivity().overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                break;
            case R.id.loading_back:
                weigtContral();
                break;
            case R.id.share_tv:
                goShare();
                break;
        }
    }

    private void goShare() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share));
        if (SettingConfig.ReadSettingString(getActivity(), SettingConfig.SEX).equals(SettingConfig.BOY)) {
            intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_boy));
        } else {
            intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_girl));
        }
        ScreenShots screenShots = new ScreenShots((View) loading_back.getParent());
        screenShots.saveBitmap(loading_back.getDrawingCache(), "share.jpg");
        Uri u = Uri.fromFile(new File(ScreenShots.IMAGE_TEMP_URI + "share.jpg"));
        intent.putExtra(Intent.EXTRA_STREAM, u);
        startActivity(Intent.createChooser(intent, getString(R.string.share)));
    }

    @Override
    public void fetchData() {
        renderUi();
    }

    private void renderUi() {
        Glide.with(this)
                .load(item.getAvatar())
                .error(R.mipmap.default_head)
                .into(avatar);

        Glide.with(this)
                .load(item.getImg_src())
                .asBitmap()
                .into(new BitmapImageViewTarget(loading_back) {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        super.onResourceReady(resource, glideAnimation);
                        ll_loading.setVisibility(View.GONE);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        ll_loading.setVisibility(View.GONE);
                    }
                });
        author.setText(item.getUname());
        info.setText(item.getContent());
    }

    private void setWallpaper() {
        if (!setting_process) {
            setting_process = true;
            MyToast.show(getActivity(), getString(R.string.setting_wallpaper));
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    try {
                        WallpaperManager wpManager = WallpaperManager.getInstance(getActivity());
                        int height = wpManager.getDesiredMinimumHeight();
                        int width = getScreen().x;
                        Bitmap resource = Glide.with(getActivity()).load(item.getImg_src()).asBitmap().into(width, height).get();
                        Bitmap result = null;
                        if (height > resource.getHeight()) {
                            result = ThumbnailUtils.extractThumbnail(resource, resource.getWidth(), resource.getHeight());
                            wpManager.suggestDesiredDimensions(resource.getWidth(), resource.getHeight());
                        } else {
                            result = ThumbnailUtils.extractThumbnail(resource, width, height);
                            wpManager.suggestDesiredDimensions(width, height);
                        }
                        wpManager.setBitmap(result);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            }.execute();


        } else {
            MyToast.show(getActivity(), getString(R.string.setting_wallpaper_process));
        }
    }

    private void setDownload() {
        if (!download_process) {
            download_process = true;
            Glide.with(getActivity()).load(item.getImg_src()).asBitmap().into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    new AsyncTask<Void, File, File>() {
                        @Override
                        protected File doInBackground(Void... params) {
                            try {
                                String dic = Environment.getExternalStorageDirectory() + "/半次元壁纸";
                                File dicf = new File(dic);
                                if (!dicf.exists()) {
                                    dicf.mkdir();
                                }
                                String name = null;
                                if (resource.hasAlpha()) {
                                    name = dic + "/" + item.getTime() + ".png";
                                } else {
                                    name = dic + "/" + item.getTime() + ".jpg";
                                }
                                File outFile = new File(name);
                                FileOutputStream fos = new FileOutputStream(outFile);
                                if (resource.hasAlpha()) {
                                    resource.compress(Bitmap.CompressFormat.PNG, 100, fos);
                                } else {
                                    resource.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                                }
                                return outFile;

                            } catch (FileNotFoundException e) {
                                return null;
                            }
                        }

                        @Override
                        protected void onPostExecute(File file) {
                            try {
                                if (file != null && !getActivity().isFinishing()) {
                                    MyToast.show(getActivity(), getString(R.string.pic_saved));
                                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                    Uri uri = Uri.fromFile(file);
                                    intent.setData(uri);
                                    getActivity().sendBroadcast(intent);
                                } else {
                                    MyToast.show(getActivity(), getString(R.string.pic_saved));
                                }
                                download_process = true;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.execute();
                }
            });
        } else {
            MyToast.show(getActivity(), getString(R.string.download_process));
        }
    }

    private void weigtContral() {
        if (display_setting.getTranslationY() == 0) {
            ObjectAnimator transTop = ObjectAnimator.ofFloat(display_setting, "translationY", UIUtils.dip2px(-74, getActivity()));
            transTop.setDuration(300);
            transTop.setInterpolator(new DecelerateInterpolator());
            transTop.start();

            ObjectAnimator transBottom = ObjectAnimator.ofFloat(rl_info.getParent(), "translationY", UIUtils.dip2px(200, getActivity()));
            transBottom.setDuration(300);
            transBottom.setInterpolator(new DecelerateInterpolator());
            transBottom.start();
        } else {
            ObjectAnimator transTop = ObjectAnimator.ofFloat(display_setting, "translationY", UIUtils.dip2px(0, getActivity()));
            transTop.setDuration(300);
            transTop.setInterpolator(new DecelerateInterpolator());
            transTop.start();

            ObjectAnimator transBottom = ObjectAnimator.ofFloat(rl_info.getParent(), "translationY", UIUtils.dip2px(0, getActivity()));
            transBottom.setDuration(300);
            transBottom.setInterpolator(new DecelerateInterpolator());
            transBottom.start();
        }
    }


    private class SuccessListener extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (setting_process) {
                MyToast.show(getActivity(), getString(R.string.setting_wallpaper_succ));
                setting_process = false;
            }
        }
    }

}
